package com.example.media.slice;

import com.example.media.ResourceTable;
import com.example.media.Utils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.global.resource.RawFileDescriptor;
import ohos.media.common.Source;
import ohos.media.player.Player;

public class PlayerAudioAbilitySlice extends AbilitySlice implements Component.ClickedListener {
    private Button mBtnAudioPlay;
    private Button mBtnAudioPause;
    private Button mBtnAudioStop;

    // 播放器
    private Player mPlayer;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_player_audio);
        mBtnAudioPlay = (Button) findComponentById(ResourceTable.Id_btn_audio_play);
        mBtnAudioPlay.setClickedListener(this);
        mBtnAudioPause = (Button) findComponentById(ResourceTable.Id_btn_audio_pause);
        mBtnAudioPause.setClickedListener(this);
        mBtnAudioStop = (Button) findComponentById(ResourceTable.Id_btn_audio_stop);
        mBtnAudioStop.setClickedListener(this);
        // 初始化播放器
        initPlayer();
    }

    @Override
    public void onClick(Component component) {
        // 播放音频
        if (component.getId() == ResourceTable.Id_btn_audio_play) {
            mPlayer.play();
        }
        // 暂停音频
        if (component.getId() == ResourceTable.Id_btn_audio_pause) {
            mPlayer.pause();
        }
        // 停止音频
        if (component.getId() == ResourceTable.Id_btn_audio_stop) {
            mPlayer.stop();
            mPlayer.release();
            initPlayer();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        mPlayer.stop();
        mPlayer.release();
    }

    /**
     * 初始化Player对象
     */
    private void initPlayer() {
        // 创建播放器对象
        mPlayer = new Player(this);
        try {
            // 打开播放音频源文件
            RawFileDescriptor fd = getResourceManager()
                    .getRawFileEntry("resources/rawfile/music.wav")
                    .openRawFileDescriptor();
            Source source = new Source(fd.getFileDescriptor(),
                    fd.getStartPosition(),
                    fd.getFileSize());
            // 设置音频源
            mPlayer.setSource(source);

        } catch (Exception e) {
            Utils.log("Exception : " + e.getLocalizedMessage());
        }
        // 准备播放
        mPlayer.prepare();
    }
}
